var express = require("express");
var router = express.Router();
var crud = require("./crud.js");

router.all("*", function(req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("X-Powered-By", ' 3.2.1');
	res.header("Content-Type", "application/json;charset=utf-8");
	next();
});


//注册

router.post("/createuser", function(req, res) {
	//接受用户参数
	var username = req.body.username;

	var password = req.body.password;

	// 给方法的参数准备好
	var sql1 = "insert into user values (?,?)";

	var sql2 = "select * from user";

	var flag=1;

	crud.selectData(sql2, function(result) {

		for(var i = 0;i < result.length;i++){

			var tem=result;

			if(tem[i].username==username){

				flag=0;

				break;
				
			}
		}	

		if(flag){

			var arr = [username, password];

			crud.insertData(sql1, arr, function(result) {
				console.log(result)
				if (result.affectedRows) {
					res.json(200, {
						"msg": "success",
						"code": 100
					})
				} else {
					// code:100成功  code：200失败
					res.send(200, {
						"msg": "error",
						"code": 200
					})
				}
			})

		}else{

			res.json(200, {
				"msg": "null",
				"code": 300
			})

		}	
	})
})

// 登录
router.post("/selectinfo", function(req, res) {
	
	var username = req.body.username;

	var password = req.body.password;

	var sql = "select * from user";

	var flag=1;

	console.log(username)

	crud.selectData(sql, function(result) {

		for(var i = 0;i < result.length;i++){

			var tem=result;

			if(tem[i].username==username){

				flag=0;

				if(tem[i].userpwd==password){

					res.json(200, {
						"msg": "success",
						"code": 100
					})
				}else{

					res.json(200, {
						"msg": "error",
						"code": 200
					})
				}
				
			}
		}	

		if(flag){

			res.json(200, {
				"msg": "null",
				"code": 300
			})
		}	
	})
})


module.exports = router;